<?php
session_start();
require_once 'config/database.php';

if (!isset($_POST['name']) || !isset($_POST['email']) || !isset($_POST['message'])) {
    $_SESSION['error_message'] = "All fields are required";
    header('Location: contact.php');
    exit();
}

$database = new Database();
$db = $database->getConnection();

$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];

// Send confirmation email to user
$user_to = $email;
$user_subject = "Thank you for contacting us";
$user_headers = "From: noreply@cardealer.com\r\n";
$user_headers .= "Content-Type: text/html; charset=UTF-8\r\n";

$user_message = "
    <p>Dear $name,</p>
    <p>Thank you for contacting us. We have received your message and will get back to you shortly.</p>
    <p>Your message details:</p>
    <p><strong>Subject:</strong> $subject</p>
    <p><strong>Message:</strong><br>$message</p>
    <br>
    <p>Best regards,<br>Car Dealer Team</p>
";

mail($user_to, $user_subject, $user_message, $user_headers);


// Store contact message in database (optional)
$query = "INSERT INTO contact_messages (name, email, subject, message) VALUES (?, ?, ?, ?)";
$stmt = $db->prepare($query);

if ($stmt->execute([$name, $email, $subject, $message])) {
    // Send email to admin
    $to = "admin@cardealer.com";
    $headers = "From: $email\r\n";
    $headers .= "Reply-To: $email\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    
    $email_message = "
        <h3>New Contact Form Submission</h3>
        <p><strong>Name:</strong> $name</p>
        <p><strong>Email:</strong> $email</p>
        <p><strong>Subject:</strong> $subject</p>
        <p><strong>Message:</strong><br>$message</p>
    ";
    
    mail($to, "New Contact Form: $subject", $email_message, $headers);
    
    $_SESSION['success_message'] = "Thank you for your message. We'll get back to you soon!";
} else {
    $_SESSION['error_message'] = "Failed to send message. Please try again.";
}

header('Location: contact.php');
exit();
?> 